package com.example.service;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.common.PageResult;
import com.example.common.enums.ErrorCodeEnum;
import com.example.exception.CustomException;
import com.example.mapper.AddressMapper;
import com.example.pojo.entity.Account;
import com.example.pojo.entity.Address;
import com.example.pojo.entity.User;
import com.example.utils.AccountUtils;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.List;

/**
 * 收货地址 service 层实现类
 */
@Service
public class AddressServiceImpl extends ServiceImpl<AddressMapper, Address> implements AddressService {

    @Resource
    private UserService userService;

    /**
     * 增加收货地址
     *
     * @param address 收货地址
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void add(Address address) {
        // 1.校验参数
        if (address == null) {
            throw new CustomException(ErrorCodeEnum.PARAM_LOST_ERROR);
        }
        this.checkAddressParam(address);
        // 2.获取用户 id
        int curUserId = this.getCurUserId();
        address.setUserId(curUserId);
        // 3.将宠物类型数据存入数据库
        this.save(address);

    }


    /**
     * 分页查询收货地址
     *
     * @param pageNum  页码
     * @param pageSize 页大小
     * @param address  条件
     * @return 分页结果
     */
    @Override
    public PageResult<Address> pageQuery(Integer pageNum, Integer pageSize, Address address) {
        // 1.校验参数
        if (pageNum == null || pageNum < 1) {
            throw new CustomException(ErrorCodeEnum.PAGE_QUERY_NUM);
        }
        if (pageSize == null || pageSize < 1 || pageSize > 100) {
            throw new CustomException(ErrorCodeEnum.PAGE_QUERY_SIZE);
        }
        // 2.创建 MybatisPlus 分页对象
        IPage<Address> pageObject = new Page<>(pageNum, pageSize);
        // 3.分页查询收货地址，只能查当前普通用户的收货地址
        int curUserId = this.getCurUserId();
        address.setUserId(curUserId);
        pageObject = this.getBaseMapper().pageQuery(pageObject, address);
        // 4.构建分页结果并返回
        return new PageResult<>(
                pageObject.getTotal(),
                pageObject.getRecords()
        );
    }

    /**
     * 根据收货地址id，查询收货地址
     *
     * @param id 收货地址id
     * @return 收货地址
     */
    @Override
    public Address queryById(Integer id) {
        // 1.校验参数
        if (id == null) {
            throw new CustomException(ErrorCodeEnum.PARAM_LOST_ERROR);
        }
        // 2.根据收货地址id，查询收货地址
        return this.lambdaQuery()
                .eq(Address::getId, id)
                .one();
    }

    /**
     * 根据条件查询全部收货地址
     *
     * @param address 条件
     * @return 收货地址列表
     */
    @Override
    public List<Address> queryAll(Address address) {
        return this.getBaseMapper().query(address);
    }

    /**
     * 修改收货地址
     *
     * @param address 收货地址
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void update(Address address) {
        // 1.校验参数
        if (address == null) {
            throw new CustomException(ErrorCodeEnum.PARAM_LOST_ERROR);
        }
        if (address.getId() == null) {
            throw new CustomException(ErrorCodeEnum.PARAM_LOST_ERROR);
        }
        this.checkAddressParam(address);

        // 2.获取用户 id
        int curUserId = this.getCurUserId();
        address.setUserId(curUserId);

        // 3.根据收货地址id，修改收货地址
        this.updateById(address);
    }

    /**
     * 根据收货地址id，删除收货地址
     *
     * @param id 收货地址id
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void delete(Integer id) {
        // 1.校验参数
        if (id == null) {
            throw new CustomException(ErrorCodeEnum.PARAM_LOST_ERROR);
        }
        // 2.根据收货地址id，删除收货地址
        this.removeById(id);
    }

    /**
     * 根据收货地址id列表，删除收货地址
     *
     * @param ids 收货地址id列表
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteBatch(List<Integer> ids) {
        // 1.校验参数
        if (CollectionUtil.isEmpty(ids)) {
            throw new CustomException(ErrorCodeEnum.PARAM_LOST_ERROR);
        }
        // 2.根据收货地址id列表，删除收货地址
        this.removeBatchByIds(ids);
    }

    /**
     * 校验收货地址
     *
     * @param address 收货地址参数
     */
    private void checkAddressParam(Address address) {
        // 1.收货人姓名不能为空
        if (StrUtil.isBlank(address.getName())) {
            throw new CustomException(ErrorCodeEnum.ADDRESS_NAME_LOST_ERROR);
        }
        // 2.收货地址不能为空
        if (StrUtil.isBlank(address.getAddress())) {
            throw new CustomException(ErrorCodeEnum.ADDRESS_LOST_ERROR);
        }
        // 3.收货人电话号不能为空
        if (StrUtil.isBlank(address.getPhone())) {
            throw new CustomException(ErrorCodeEnum.ADDRESS_PHONE_LOST_ERROR);
        }
    }

    /**
     * 获取用户 id
     *
     * @return 用户 id
     */
    private int getCurUserId() {
        Account currentLoginAccount = AccountUtils.getCurrentLoginAccount();
        if (currentLoginAccount == null) {
            throw new CustomException(ErrorCodeEnum.GET_CUR_USER_ERROR);
        }
        return this.userService.lambdaQuery()
                .eq(User::getUsername, currentLoginAccount.getUsername())
                .one()
                .getId();
    }
}
